import { io } from "socket.io-client";
import { useEffect, useRef, useCallback, useState } from "react";

const useSocket = (url, options = {}) => {
    const socket = useRef(null)

    useEffect(() => {
        socket.current = io(url, options)
        return () => {
            socket.current.disconnect();
        }
    }, [])

    const onSocketEvents = useCallback((events) => {
        if (!socket.current) return
        Object.keys(events).forEach((event) => {
            socket.current.on(event, events[event])
        })
    }, [])

    const offSocketEvents = useCallback((events) => {
        if (!socket.current) return
        Object.keys(events).forEach((event) => {
            socket.current.off(event, events[event])
        })
    }, [])

    const emitSocketEvents = useCallback((event, data) => {
        if (!socket.current) return
        socket.current.emit(event, data)
    }, [])

    return {
        socket,
        onSocketEvents,
        offSocketEvents,
        emitSocketEvents
    }
}

export default useSocket;